<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'

const route = useRoute()
const searchQuery = ref('')
const searchResults = ref([])
const loading = ref(false)

// 获取类别对应的图标
const getCategoryIcon = (category) => {
  const categoryIcons = {
    '女装': '👗',
    '男装': '👔',
    '鞋靴': '👟',
    '箱包': '👜',
    '数码': '📱',
    '家电': '📺',
    '家居': '🏠',
    '美妆': '💄',
    '母婴': '👶',
    '食品': '🍔'
  }
  return categoryIcons[category] || '🛍️'
}

// 获取默认商品图片
const getDefaultImage = (category) => {
  const categoryImages = {
    '女装': 'https://via.placeholder.com/300?text=女装',
    '男装': 'https://via.placeholder.com/300?text=男装',
    '鞋靴': 'https://via.placeholder.com/300?text=鞋靴',
    '箱包': 'https://via.placeholder.com/300?text=箱包',
    '数码': 'https://via.placeholder.com/300?text=数码',
    '家电': 'https://via.placeholder.com/300?text=家电',
    '家居': 'https://via.placeholder.com/300?text=家居',
    '美妆': 'https://via.placeholder.com/300?text=美妆',
    '母婴': 'https://via.placeholder.com/300?text=母婴',
    '食品': 'https://via.placeholder.com/300?text=食品'
  }
  return categoryImages[category] || 'https://via.placeholder.com/300?text=商品图片'
}

// 模拟搜索商品数据
const mockProducts = [
  {
    id: 1,
    name: '时尚连衣裙',
    category: '女装',
    price: 199,
    originalPrice: 299,
    image: 'https://img.alicdn.com/imgextra/i1/O1CN01e0Z4fO1yG7g7Q1Zfo_!!6000000006889-0-picassoopen.jpg',
    sales: 1234
  },
  {
    id: 2,
    name: '男士休闲鞋',
    category: '鞋靴',
    price: 299,
    originalPrice: 399,
    image: 'https://img.alicdn.com/imgextra/i4/O1CN012V4u0T1z6Q7O9Z0hJ_!!6000000006105-0-picassoopen.jpg',
    sales: 2345
  },
  {
    id: 3,
    name: '智能手表',
    category: '数码',
    price: 799,
    originalPrice: 999,
    image: 'https://img.alicdn.com/imgextra/i1/O1CN01X0FzNQ27YtU4K2bVQ_!!6000000007990-0-picassoopen.jpg',
    sales: 3456
  },
  {
    id: 4,
    name: '护肤套装',
    category: '美妆',
    price: 399,
    originalPrice: 599,
    image: 'https://img.alicdn.com/imgextra/i3/O1CN013vR93t1eZ2wY7Y6qL_!!6000000006001-0-picassoopen.jpg',
    sales: 4567
  },
  {
    id: 5,
    name: '运动背包',
    category: '箱包',
    price: 159,
    originalPrice: 259,
    image: 'https://img.alicdn.com/imgextra/i2/O1CN01z8X2ZQ1vJ1z6Z8X2Z_!!6000000006227-0-picassoopen.jpg',
    sales: 5678
  },
  {
    id: 6,
    name: '厨房电器',
    category: '家电',
    price: 499,
    originalPrice: 699,
    image: 'https://img.alicdn.com/imgextra/i4/O1CN01x9KZ0h1zJ1Z8X2ZQ_!!6000000006228-0-picassoopen.jpg',
    sales: 6789
  },
  {
    id: 7,
    name: '家居拖鞋',
    category: '家居',
    price: 29,
    originalPrice: 49,
    image: 'https://img.alicdn.com/imgextra/i1/O1CN01n8X2ZQ1vJ1z6Z8X2Z_!!6000000006229-0-picassoopen.jpg',
    sales: 7890
  },
  {
    id: 8,
    name: '婴儿奶粉',
    category: '母婴',
    price: 199,
    originalPrice: 299,
    image: 'https://img.alicdn.com/imgextra/i3/O1CN01k8X2ZQ1vJ1z6Z8X2Z_!!6000000006230-0-picassoopen.jpg',
    sales: 8901
  }
]

// 从路由参数中获取搜索词并执行搜索
onMounted(() => {
  const query = route.query.q
  if (query) {
    searchQuery.value = query
    performSearch(query)
  }
})

// 执行搜索
const performSearch = (query) => {
  if (!query || query.trim() === '') return
  
  loading.value = true
  
  // 模拟搜索延迟
  setTimeout(() => {
    // 简单的模拟搜索逻辑：过滤商品名称中包含搜索词的商品
    searchResults.value = mockProducts.filter(product => 
      product.name.toLowerCase().includes(query.toLowerCase())
    )
    loading.value = false
  }, 500)
}

// 处理搜索表单提交
const handleSearch = () => {
  performSearch(searchQuery.value)
}

// 模拟添加到购物车
const addToCart = (product) => {
  console.log('添加到购物车:', product)
  alert(`已将「${product.name}」添加到购物车`)
  
  // 简单的购物车数据存储模拟
  const cart = localStorage.getItem('cart')
  const cartItems = cart ? JSON.parse(cart) : []
  cartItems.push(product)
  localStorage.setItem('cart', JSON.stringify(cartItems))
}
</script>

<template>
  <div class="search-page">
    <div class="container">
      <div class="search-header">
        <h2>搜索结果</h2>
        <div class="search-box">
          <input 
            type="text" 
            v-model="searchQuery" 
            placeholder="搜索商品"
            @keyup.enter="handleSearch"
            class="search-input"
          />
          <button @click="handleSearch" class="search-btn">搜索</button>
        </div>
      </div>
      
      <!-- 搜索结果区域 -->
      <div class="search-results">
        <!-- 加载状态 -->
        <div v-if="loading" class="loading">
          <p>正在搜索中...</p>
        </div>
        
        <!-- 有搜索查询但无结果 -->
        <div v-else-if="searchQuery && searchResults.length === 0" class="no-results">
          <p>没有找到相关商品，请尝试其他关键词</p>
        </div>
        
        <!-- 显示搜索结果 -->
        <div v-else-if="searchResults.length > 0" class="products-grid">
            <div v-for="product in searchResults" :key="product.id" class="product-card">
              <div class="product-image">
                <img :src="product.image || getDefaultImage(product.category)" :alt="product.name" />
                <button class="add-to-cart" @click="addToCart(product)">加入购物车</button>
                <div v-if="product.category" class="category-badge">
                  <span class="category-badge-icon">{{ getCategoryIcon(product.category) }}</span>
                  <span class="category-badge-name">{{ product.category }}</span>
                </div>
              </div>
              <div class="product-info">
                <div class="product-title">{{ product.name }}</div>
                <div class="product-price">
                  <span class="price">¥{{ product.price }}</span>
                  <span class="original-price">¥{{ product.originalPrice }}</span>
                </div>
                <div class="product-sales">已售 {{ product.sales }}</div>
                <router-link :to="{ name: 'shop', params: { id: product.shopId || '1' } }" class="shop-link">
                  <span class="shop-name">查看店铺</span>
                </router-link>
              </div>
            </div>
          </div>
        
        <!-- 未执行搜索时的提示 -->
        <div v-else class="search-tip">
          <p>请输入关键词搜索商品</p>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.search-page {
  background-color: #f5f5f5;
  min-height: 60vh;
  padding: 20px 0;
  width: 100%;
}

.search-header {
  background-color: #fff;
  padding: 20px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  margin-bottom: 0;
  width: 100%;
}

.search-header h2 {
  font-size: 24px;
  color: #333;
  margin-bottom: 15px;
}

.search-box {
  display: flex;
}

/* 类别标签样式 */
.product-image {
  position: relative;
  overflow: hidden;
}

.category-badge {
  position: absolute;
  top: 8px;
  left: 8px;
  background-color: rgba(255, 255, 255, 0.9);
  color: #666;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  z-index: 1;
  opacity: 0;
  transform: translateY(-10px);
  transition: all 0.3s ease;
  backdrop-filter: blur(2px);
  display: flex;
  align-items: center;
  gap: 3px;
}

.product-card:hover .category-badge {
  opacity: 1;
  transform: translateY(0);
  background-color: white;
  color: #ff0036;
}

.category-badge-icon {
  font-size: 14px;
}

.category-badge-name {
  font-weight: 500;
}
  max-width: 600px;
}

.search-input {
  flex: 1;
  height: 40px;
  padding: 0 15px;
  border: 2px solid #ff0036;
  border-right: none;
  font-size: 14px;
  outline: none;
}

.search-btn {
  width: 80px;
  height: 40px;
  background-color: #ff0036;
  color: white;
  border: none;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.search-btn:hover {
  background-color: #e60029;
}

.search-results {
  background-color: #fff;
  padding: 20px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  width: 100%;
}

.loading,
.no-results,
.search-tip {
  text-align: center;
  padding: 60px 0;
  color: #666;
  font-size: 16px;
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
}

.product-card {
  transition: transform 0.3s, box-shadow 0.3s;
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.product-card .product-image {
  position: relative;
  height: 200px;
  margin-bottom: 10px;
  overflow: hidden;
}

.product-card .product-image img {
  width: 100%;
  height: 100%;
  object-fit: contain;
  transition: transform 0.3s;
}

.product-card:hover .product-image img {
  transform: scale(1.05);
}

.add-to-cart {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 36px;
  background-color: #ff0036;
  color: white;
  border: none;
  font-size: 14px;
  cursor: pointer;
  opacity: 0;
  transition: opacity 0.3s;
}

.product-card:hover .add-to-cart {
  opacity: 1;
}

.add-to-cart:hover {
  background-color: #e60029;
}

.product-title {
  font-size: 14px;
  color: #333;
  margin-bottom: 5px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-price {
  margin-bottom: 5px;
}

.price {
  font-size: 18px;
  color: #ff0036;
  font-weight: bold;
  margin-right: 5px;
}

.original-price {
  font-size: 14px;
  color: #999;
  text-decoration: line-through;
}

.product-sales {
  font-size: 12px;
  color: #999;
}

.shop-link {
  text-decoration: none;
  color: #1989fa;
  font-size: 12px;
  margin-top: 5px;
  display: inline-block;
}

.shop-link:hover {
  color: #409eff;
}

@media (max-width: 1200px) {
  .products-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 768px) {
  .products-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .search-box {
    max-width: 100%;
  }
}
</style>